package config

import (
	"context"
	"fmt"
	"karnin-zero-admin/service/sys/api/internal/svc"
	"karnin-zero-admin/service/sys/api/internal/types"
	"karnin-zero-admin/service/sys/model"
	"strconv"

	"github.com/tal-tech/go-zero/core/logx"
)

type ConfigListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewConfigListLogic(ctx context.Context, svcCtx *svc.ServiceContext) ConfigListLogic {
	return ConfigListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ConfigListLogic) ConfigList(req types.ConfigListRequest) (resp *types.ConfigListResponse, err error) {

	var page = 1
	var pageSize = 20
	if req.Page != 0 {
		page = req.Page
	}
	if req.PageSize != 0 {
		pageSize = req.PageSize
	}
	var items []model.Config
	query := l.svcCtx.GormDB
	queryCount := l.svcCtx.GormDB
	//分页
	var total int64 = 0
	queryCount = queryCount.Model(&model.Config{})
	//筛选条件
	if req.Key != "" {
		fmt.Println(req.Key)
		queryCount = queryCount.Where("`key` = ?", req.Key)
		query = query.Where("`key` = ?", req.Key)
	}
	if req.Value != "" {
		queryCount = queryCount.Where("value = ?", req.Value)
		query = query.Where("value = ?", req.Value)
	}
	//查询你
	queryCount.Count(&total)
	query.Limit(pageSize).Offset((page - 1) * pageSize).Order("id desc").Find(&items)

	//赋值
	var list []types.ConfigListItem
	for _, item := range items {
		var configListItem types.ConfigListItem
		configListItem.ID = int(item.ID)
		configListItem.Key = item.Key
		configListItem.Value = item.Value
		configListItem.Comment = item.Comment
		configListItem.CreatedAt = item.CreatedAt.Format("2006 01 02 15:04:05")
		list = append(list, configListItem)
	}

	//int64转int
	t, _ := strconv.Atoi(strconv.FormatInt(total, 10))
	return &types.ConfigListResponse{
		List:     list,
		Page:     page,
		PageSize: pageSize,
		Total:    t,
	}, nil
}
